package com.xiaojie.demo;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import static com.xiaojie.cofnig.RabbitMQConfig.DEAD_LETTER_QUEUEA_NAME;
import static com.xiaojie.cofnig.RabbitMQConfig.ITEM_QUEUE;


/**
 * @author wangye
 * @classname Reciver
 * @date 2021/4/12 15:30
 **/
@RestController
@RequestMapping("/demo")
public class Reciver {

    @Autowired
    private RabbitTemplate template;

    /**
     * 推模式
     *
     * @param message
     * @auther wangye
     * @date 2021/4/13
     */
    @RabbitListener(queues = ITEM_QUEUE)
    public void recive(Message message, Channel channel) throws IOException, InterruptedException {
        //设置消费者最多为确认消息数量
        channel.basicQos(1);
//        Thread.sleep(3000L);
        boolean ack = true;
        String msg = new String(message.getBody());
        if (msg.contains("dead"))
            ack = false;
        if (!ack) {
            System.out.println("拒绝消息：" + msg);
            throw new RuntimeException("拒绝消息");
        } else {
            System.out.println("接收消息：" + msg);
        }
    }

    /**
     * 拉模式
     *
     * @param
     * @auther wangye
     * @date 2021/4/13
     */
    @RequestMapping(value = "recive", method = RequestMethod.GET)
    public void recive() throws Exception {
        Message message = template.receive(ITEM_QUEUE, 2000);
        String msg = new String(message.getBody(), "UTF-8");
        System.out.println("收到消息:" + msg);
    }

    @RabbitListener(queues = DEAD_LETTER_QUEUEA_NAME)
    public void receiveA(Message message, Channel channel) throws IOException {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("收到死信消息A：" + new String(message.getBody()));
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @RabbitListener(queues = "erp")
    public void receiveC(Message message, Channel channel) throws IOException {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("收到ERP消息：" + new String(message.getBody()));
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
